<template>
  <div class="ignore-rule-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">黑名单忽略规则管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加规则
          </el-button>
        </div>
      </template>

      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="ignore_type" label="忽略类型" width="150">
          <template #default="{ row }">
            <el-tag>{{ row.ignore_type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ignore_val" label="忽略值" min-width="200" />
        <el-table-column prop="enabled" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.enabled"
              @change="handleStatusChange(row)"
              :loading="row.statusLoading"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="忽略类型" prop="ignore_type">
          <el-select
            v-model="form.ignore_type"
            placeholder="请选择忽略类型"
            style="width: 100%"
          >
            <el-option label="Set名称" value="set" />
            <el-option label="IP地址" value="ip" />
            <el-option label="规则" value="rule" />
          </el-select>
        </el-form-item>
        <el-form-item label="忽略值" prop="ignore_val">
          <el-input
            v-model="form.ignore_val"
            placeholder="请输入忽略值"
            :rows="3"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="启用状态" prop="enabled">
          <el-switch v-model="form.enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getAllIgnoreRules,
  insertIgnoreRule,
  updateIgnoreRule,
  deleteIgnoreRule,
} from '@/api/ignoreRule'
import type { IgnoreRule, InsertIgnoreRuleRequest } from '@/types/ignoreRule'

// 数据
const tableData = ref<IgnoreRule[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加规则')
const formRef = ref<FormInstance>()
const submitting = ref(false)

// 表单数据
const form = reactive<InsertIgnoreRuleRequest & { id?: number }>({
  ignore_type: '',
  ignore_val: '',
  enabled: true,
})

// 表单验证规则
const rules: FormRules = {
  ignore_type: [
    { required: true, message: '请选择忽略类型', trigger: 'change' },
  ],
  ignore_val: [
    { required: true, message: '请输入忽略值', trigger: 'blur' },
  ],
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getAllIgnoreRules()
    tableData.value = res.update_ignore_rule_request || []
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 添加
const handleAdd = () => {
  dialogTitle.value = '添加规则'
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: IgnoreRule) => {
  dialogTitle.value = '编辑规则'
  form.id = row.id
  form.ignore_type = row.ignore_type
  form.ignore_val = row.ignore_val
  form.enabled = row.enabled
  dialogVisible.value = true
}

// 状态切换
const handleStatusChange = async (row: IgnoreRule) => {
  try {
    row.statusLoading = true
    await updateIgnoreRule({
      id: row.id,
      ignore_type: row.ignore_type,
      ignore_val: row.ignore_val,
      enabled: row.enabled,
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    // 失败时恢复状态
    row.enabled = !row.enabled
  } finally {
    row.statusLoading = false
  }
}

// 删除
const handleDelete = async (row: IgnoreRule) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除规则 "${row.ignore_val}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await deleteIgnoreRule(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    submitting.value = true
    try {
      if (form.id) {
        // 编辑
        await updateIgnoreRule({
          id: form.id,
          ignore_type: form.ignore_type,
          ignore_val: form.ignore_val,
          enabled: form.enabled,
        })
      } else {
        // 添加
        await insertIgnoreRule({
          ignore_type: form.ignore_type,
          ignore_val: form.ignore_val,
          enabled: form.enabled,
        })
      }
      dialogVisible.value = false
      loadData()
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitting.value = false
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = undefined
  form.ignore_type = ''
  form.ignore_val = ''
  form.enabled = true
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.ignore-rule-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
